from typing import Union, List, Optional
from fastapi import FastAPI, Form, File, UploadFile
from pydantic import BaseModel, Field, ValidationError, validator, validators
import uvicorn
from datetime import date
import sys
import os

app = FastAPI()


@app.post("/create_file")
async def create_file(file: bytes = File()):
    print("file: ", file)
    return {"file_size": len(file)}

@app.post("/create_multi_files")
async def create_multi_files(files: List[bytes] = File()):
    # 适合小文件上传
    # print("file", files)
    for file in files:
        print("file: ", len(file))

    return {"file_sizes": [len(file) for file in files]}


# file: UploadFile适合大文件上传
@app.post("/upload_big_size_file")
async def upload_big_size_file(file: UploadFile):
    with open(f"{file.filename}", "wb") as f:
        for chunk in iter(lambda: file.file.read(1024), b''):
            f.write(chunk)

    return {"filename": file.filename}

@app.post("/upload_multi_big_size_file")
async def upload_multi_big_size_file(files: List[UploadFile]):
    return {"filenames": [file.filename for file in files]}


if __name__ == '__main__':
    print(sys.argv)

    # 获取当前文件的完整路径
    file_path = __file__
    # 获取文件名
    file_name = os.path.basename(file_path)
    print(file_name)

    start_args = file_name.split(".py")[0] + ":app"

    uvicorn.run(start_args, host="127.0.0.1", port=8000, reload=True)